﻿Imports System.Data.SqlClient

Public Class frmUtama
    Dim WaktuMulai As Date
    Dim Copier As SqlBulkCopy
    Dim batalkan_copy As Boolean = False
    Dim numberOfRows As Long

    Private Sub SqlBulkCopy_Notify(sender As Object, e As SqlRowsCopiedEventArgs)
        e.Abort = batalkan_copy

        Try
            Dim percent As Double = (e.RowsCopied / numberOfRows) * 100
            prgProgress.Value = CInt(percent)
            lblProgress.Text = Math.Round(percent, 0) & "%"
        Catch ex As Exception

        End Try
    End Sub

#Region " Database GroupBox "
#Region " Source Database "
    Private Sub lbAturDb1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lbAturDb1.LinkClicked
        Dim ftm As New frmServer
        ftm.ConnectionString = GlobalSourceConnectionString
        If ftm.ShowDialog = Windows.Forms.DialogResult.OK Then
            GlobalSourceConnectionString = ftm.ConnectionString
            Dim pesan As String = ""
            Dim cn As SqlConnection = ConnectSQL(GlobalSourceConnectionString, pesan)
            If cn IsNot Nothing Then
                lblDb1.Text = "Siap."
            Else
                lblDb1.Text = "Koneksi gagal."
            End If
        End If
    End Sub
#End Region

#Region " Destination Database "
    Private Sub lbAturDb2_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lbAturDb2.LinkClicked
        Dim ftm As New frmServer
        ftm.ConnectionString = GlobalDestinationConnectionString
        If ftm.ShowDialog = Windows.Forms.DialogResult.OK Then
            GlobalDestinationConnectionString = ftm.ConnectionString
            Dim pesan As String = ""
            Dim cn As SqlConnection = ConnectSQL(GlobalDestinationConnectionString, pesan)
            If cn IsNot Nothing Then
                lblDb2.Text = "Siap."
            Else
                lblDb2.Text = "Koneksi gagal."
            End If
        End If
    End Sub
#End Region
#End Region

    Private Sub tmrETA_Tick(sender As System.Object, e As System.EventArgs) Handles tmrETA.Tick
        If prgProgress.Value <> 100 Then
            Try
                Dim eta_detik As Long = (DateTime.Now - WaktuMulai).TotalSeconds / prgProgress.Value * (prgProgress.Maximum - prgProgress.Value)
                Dim eta_span As TimeSpan = TimeSpan.FromSeconds(eta_detik)
                Dim sb As New System.Text.StringBuilder
                With sb
                    .Append("Tinggal ")
                    If eta_span.Hours <> 0 Then
                        .Append(eta_span.Hours & " jam ")
                    End If
                    If eta_span.Minutes <> 0 Then
                        .Append(eta_span.Minutes & " menit ")
                    End If
                    If eta_span.Seconds <> 0 Then
                        .Append(eta_span.Seconds & " detik")
                    End If
                End With
                lblETA.Text = sb.ToString
            Catch ex As Exception
                lblETA.Text = "Kesalahan aritmatika."
            End Try
        Else
            lblETA.Text = String.Empty
        End If
    End Sub

    Private Sub cmdSettings_Click(sender As System.Object, e As System.EventArgs) Handles cmdSettings.Click
        frmPengaturan.ShowDialog()
    End Sub

    Private Sub cmdTambahAntrian_Click(sender As System.Object, e As System.EventArgs) Handles cmdTambahAntrian.Click
        If lblDb1.Text <> "Siap." Then
            MsgBox("Database masih bermasalah. Silahkan perbaiki.")
            Return
        End If
        Dim tbh As New frmTambahAntrian
        If tbh.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim item = lvTabel.Items.Add(tbh.TabelSumber)
            item.SubItems.Add("-->")
            item.SubItems.Add(tbh.TabelTujuan)
        End If
    End Sub

    Private Sub cmdHapusAntrian_Click(sender As System.Object, e As System.EventArgs) Handles cmdHapusAntrian.Click
        If lvTabel.FocusedItem Is Nothing Then
            MsgBox("Silahkan pilih satu item dari daftar dibawah.", vbExclamation, "Tidak terpilih")
            Return
        Else
            lvTabel.Items.Remove(lvTabel.FocusedItem)
        End If
    End Sub

    '--------------------MAIN PROCESSING--------------------------------
    Private Sub cmdStart_Click(sender As System.Object, e As System.EventArgs) Handles cmdStart.Click
        'Cek database

        'Cek tabel

        'Disable semua control

        'Persiapan variabel
        Dim pesan As String = ""
        Dim sourceCN As SqlConnection = ConnectSQL(GlobalSourceConnectionString, pesan)
        If sourceCN Is Nothing Then
            MsgBox("Maaf, koneksi ke server database sumber gagal." & vbCrLf & pesan, vbExclamation, "Gagal koneksi database")
            Return
        End If
        Dim destinationCN As SqlConnection = ConnectSQL(GlobalDestinationConnectionString, "")
        If destinationCN Is Nothing Then
            MsgBox("Maaf, koneksi ke server database tujuan gagal.", vbExclamation, "Gagal koneksi database")
            Return
        End If

        'Mulai copy.
        bwCopier.RunWorkerAsync(lvTabel.Items)
    End Sub

    Private Sub bwCopier_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwCopier.DoWork
        'Mulai proses copy
        Dim Tables As ListView.ListViewItemCollection = DirectCast(e.Argument, ListView.ListViewItemCollection)
        For Each item As ListViewItem In Tables
            'Perhitungan progress
            WaktuMulai = Now
            Me.Invoke(New MethodInvoker(Sub() tmrETA.Start()))

            'Deklarasi variabel
            Dim sourceCN As SqlConnection = ConnectSQL(GlobalSourceConnectionString, "")
            Dim destCN As SqlConnection = ConnectSQL(GlobalDestinationConnectionString, "")
            Dim sourceTableName As String = item.SubItems(0).Text
            Dim sourceTableCount As Long = CountTableRows(sourceCN, sourceTableName)
            Dim destTableName As String = item.SubItems(1).Text

            'Cek table
            If My.Settings.DropTableFirst Then
                DropAndCreateTable(sourceCN, sourceTableName, destCN, destTableName)
            End If

            Copier = New SqlBulkCopy(GlobalDestinationConnectionString)
            AddHandler Copier.SqlRowsCopied, AddressOf SqlBulkCopy_Notify
            With Copier
                .BatchSize = If(My.Settings.BatchSize > sourceTableCount, sourceTableCount / 4, My.Settings.BatchSize)
                .BulkCopyTimeout = My.Settings.Timeout
                .NotifyAfter = .BatchSize / 2
                .DestinationTableName = destTableName
            End With

            Dim cmd_baca As New SqlCommand("SELECT * FROM [dbo].[" & sourceTableName & "]", sourceCN)

            '====================================================
            Dim baca As SqlDataReader = cmd_baca.ExecuteReader()
            Copier.WriteToServer(baca)
            '====================================================

            baca.Close()
            RemoveHandler Copier.SqlRowsCopied, AddressOf SqlBulkCopy_Notify
        Next
        
    End Sub

    Private Sub cmdAbout_Click(sender As System.Object, e As System.EventArgs) Handles cmdAbout.Click
        Dim cna As SqlConnection = ConnectSQL(GlobalSourceConnectionString, "")
        'Dim cmd As New SqlDataAdapter("SELECT TOP 1 * FROM [ActivePerpus].[dbo].[Buku]", cna)
        'Dim temp_ds As New DataSet
        Dim cm As New SqlCommand("SELECT TOP 1 * FROM [ActivePerpus].[dbo].[Buku]", cna)
        Dim rd As SqlDataReader = cm.ExecuteReader
        Dim scheme As DataTable = rd.GetSchemaTable 'temp_ds.Tables(0)
        Dim hasii As String = CreateTableSQL(scheme, "Buku")
        rd.Close()
        rd.Dispose()
        cna.Close()
    End Sub
End Class
